package com.web.graduationpro.manager.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.web.graduationpro.dao.service.InstrumentCourseService;
import com.web.graduationpro.dao.service.InstrumentSchoolService;
import com.web.graduationpro.model.InstrumentCourse;
import com.web.graduationpro.model.InstrumentSchool;

@Controller
@RequestMapping("/manager/course/*")
public class ManagerCourseController {

	@Resource(name="instrumentSchoolServiceImpl")
	private InstrumentSchoolService instrumentSchoolServiceImpl;
	
	@Resource(name="instrumentCourseServiceImpl")
	private InstrumentCourseService instrumentCourseServiceImpl;
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)  
    public String index() {  
        return "/manager/course/index";
    } 
	
	@RequestMapping(value = "getCourse", method = RequestMethod.POST)  
    public void  getData(HttpServletRequest request,HttpServletResponse reponse) { 
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		int startNum = 0;
		int pageNum = 10;
		String start = request.getParameter("start");
		if(start!=null && !"".equals(start.trim())){
			startNum = Integer.parseInt(start);
		}
		String pageSize = request.getParameter("pageSize");
        if(pageSize!=null && !"".equals(pageSize.trim())){
        	pageNum = Integer.parseInt(pageSize);
		}
        
        String queryHql = "  FROM InstrumentCourse ic WHERE ic.id!=0";
        String queryCountHql = "SELECT count(*) From InstrumentCourse ic WHERE ic.id!=0 ";
        List<Object> searchValues = new ArrayList<Object>();
        String keyword = request.getParameter("keyword");
        if(keyword!=null && !"".equals(keyword.trim())){
        	searchValues.add("%"+keyword+"%");
        	queryHql += " AND ic.name like ?";
        	queryCountHql += " AND ic.name like ?";
        }
      
        List<InstrumentCourse> datas = null;
        
        Object[] cses = null;
        if(searchValues!=null && searchValues.size()!=0){
        	cses = new Object[searchValues.size()];
        	for(int i=0;i<searchValues.size();i++){
        		cses[i] = searchValues.get(i);
        	}
        	datas = instrumentCourseServiceImpl.findByPage(queryHql, cses , startNum, pageNum);
        }else{
    		datas = instrumentCourseServiceImpl.findByPage(queryHql, startNum, pageNum);	
        }
		
		String result = "";
		if(datas!=null && datas.size()!=0){
			List<InstrumentCourse> returnResultList = new ArrayList<InstrumentCourse>();
			for(InstrumentCourse ic:datas){
				ic.setSsSchool(ic.getInstrumentSchool().getSchoolName());
				returnResultList.add(ic);
			}
			JsonConfig jc = new JsonConfig();
			jc.setExcludes(new String[]{"instrumentSchool","applys"});
			JSONArray json = JSONArray.fromObject(returnResultList,jc);
			result = json.toString();
		}
		
		int count = 0;
		 if(searchValues!=null && searchValues.size()!=0){
			 count = instrumentCourseServiceImpl.findTotalCount(queryCountHql, cses);
		 }else{
			 count = instrumentCourseServiceImpl.findTotalCount(InstrumentCourse.class);
		 }
		 String str = "{\"total\":" + count + ",\"rows\":" + result.toString() + "}";
         if("".equals(result.trim())){
        	 str = "{\"total\":0,\"rows\":[]}";
         }
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(str);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)  
    public void saveOrUpdate(HttpServletRequest request,HttpServletResponse reponse) { 
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		reponse.setContentType("text/html;charset=UTF-8");
		
		int handle = 0;
		String id = request.getParameter("id");
		InstrumentCourse ic = null;
		if(id!=null && !"".equals(id.trim())){
			ic = (InstrumentCourse) instrumentCourseServiceImpl.findById(InstrumentCourse.class, Integer.parseInt(id));
			handle = 1;
		}else{
			ic = new InstrumentCourse();
		}
		String name = request.getParameter("name");
		String ssSchool = request.getParameter("ssSchool");
		String cdescribe = request.getParameter("cdescribe");
		String lessonsTime = request.getParameter("lessonsTime");
		
		ic.setName(name);
		InstrumentSchool is = (InstrumentSchool)instrumentSchoolServiceImpl.findById(InstrumentSchool.class, Integer.parseInt(ssSchool));
		if(is!=null){
			ic.setInstrumentSchool(is);
		}
		ic.setCdescribe(cdescribe);
		ic.setLessonsTime(lessonsTime);
		
		String registerStatus = "error";
		try{
			if(handle==0){
				instrumentSchoolServiceImpl.save(ic);
			}else if(handle==1){
				instrumentSchoolServiceImpl.updata(ic);
			}
			registerStatus = "success";
		}catch(Exception e){
			e.printStackTrace();
		}

		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(registerStatus);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    } 
	
	@RequestMapping(value = "delete", method = RequestMethod.POST)  
    public void  delete(HttpServletRequest request,HttpServletResponse reponse) { 
		String deleteids = request.getParameter("deleteids");
		String result = "error";
		if(deleteids!=null && !"".equals(deleteids.trim())){
			 String[] deleteIdSplit = deleteids.split(",");
			 String hql = "";
			 for(int i=0;i<deleteIdSplit.length;i++){
				if(!"".equals(deleteIdSplit[i].trim())){
					 if(i==0) {
						 hql = "DELETE FROM InstrumentCourse where id="+deleteIdSplit[i];
					  } else {
						 hql =hql + " or id="+deleteIdSplit[i];
					  }
				}
			 }

			 if(!"".equals(hql.trim())){
				 int deleteResult = instrumentSchoolServiceImpl.delete(hql);
				 if(deleteResult>0){
					result = "success";
				 } 
			 }
		}
		try {
			PrintWriter writer = reponse.getWriter();
			writer.write(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
